package com.cskaoyan.service.impl;


import com.cskaoyan.mapper.*;
import com.cskaoyan.model.*;
import com.cskaoyan.service.RegionService;
import com.cskaoyan.utils.MyBatisUtil;
import org.apache.ibatis.session.SqlSession;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class RegionServiceImpl implements RegionService {
    @Override
    public List<MarketRegion> getList() {
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        MarketRegionMapper regionMapper = sqlSession.getMapper(MarketRegionMapper.class);
        List<MarketRegion> provinceList = regionMapper.selectByType(((byte) 1));
        List<MarketRegion> cityList = regionMapper.selectByType((byte) 2);
        List<MarketRegion> areaList = regionMapper.selectByType((byte) 3);

        Map<Integer, List<MarketRegion>> cityIdAreaListMap = areaList.stream().collect(Collectors.groupingBy(MarketRegion::getPid));
        cityList.forEach(city ->{city.setChildren(cityIdAreaListMap.get(city.getId()));});
        Map<Integer, List<MarketRegion>> provinceIdCityListMap = cityList.stream().collect(Collectors.groupingBy(MarketRegion::getPid));
        provinceList.forEach(province -> {province.setChildren(provinceIdCityListMap.get(province.getId()));});

        return provinceList;
    }
}
